package com.ruyiadmin.springboot.service.impls.system;

import com.alibaba.fastjson.JSON;
import com.ruyiadmin.springboot.common.beans.system.SystemCacheConfig;
import com.ruyiadmin.springboot.common.components.core.RuYiRedisComponent;
import com.ruyiadmin.springboot.common.core.system.entities.QueryResult;
import com.ruyiadmin.springboot.domain.dto.system.SysMenuDTO;
import com.ruyiadmin.springboot.domain.entity.system.SysLanguage;
import com.ruyiadmin.springboot.domain.entity.system.SysMenu;
import com.ruyiadmin.springboot.domain.entity.system.SysMenuLanguage;
import com.ruyiadmin.springboot.repository.system.ISysMenuRepository;
import com.ruyiadmin.springboot.service.iservices.system.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<ISysMenuRepository, SysMenu> implements ISysMenuService {

    //region 实现类私有属性

    private final RuYiRedisComponent redisUtils;
    private final ModelMapper modelMapper;
    private final SystemCacheConfig systemCacheConfig;

    //endregion

    //region 加载系统菜单缓存

    /**
     * 加载系统菜单缓存
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void loadSysMenuCache() {
        List<SysMenuDTO> menus = new ArrayList<>();
        List<SysMenu> list = this.list();
        for (SysMenu menu : list) {
            menus.add(this.modelMapper.map(menu, SysMenuDTO.class));
        }
        this.redisUtils.set(systemCacheConfig.getMenuCacheName(), JSON.toJSONString(menus));
        log.info("RuYiAdmin sys menus cache loaded");
    }

    //endregion

    //region 清理系统菜单缓存

    /**
     * 清理系统菜单缓存
     */
    @Override
    public void clearSysMenuCache() {
        this.redisUtils.del(systemCacheConfig.getMenuCacheName());
        log.info("RuYiAdmin sys menus cache cleared");
    }

    //endregion

    //region 查询菜单列表

    /**
     * 查询菜单列表
     *
     * @return QueryResult
     */
    @Override
    public QueryResult<SysMenuDTO> getMenuTreeNodes() {
        Object value = this.redisUtils.get(systemCacheConfig.getMenuCacheName());
        List<SysMenuDTO> menus = JSON.parseArray(value.toString(), SysMenuDTO.class);

        List<SysMenuDTO> parentMenus = menus.stream().
                filter(t -> StringUtils.isEmpty(t.getParentId())).
                sorted(Comparator.comparing(SysMenuDTO::getSerialNumber)).
                collect(Collectors.toList());

        for (SysMenuDTO menu : parentMenus) {
            //递归子节点
            this.initMenuChildren(menu, menus);
        }

        List<SysMenuDTO> result = new ArrayList<>(parentMenus);

        return QueryResult.success(parentMenus.size(), result);
    }

    //endregion

    //region 实现类私有方法

    /**
     * 递归子节点
     *
     * @param root  根节点
     * @param menus 菜单列表
     */
    private void initMenuChildren(SysMenuDTO root, List<SysMenuDTO> menus) {

        //region 初始化菜单多语

        Object value = this.redisUtils.get(this.systemCacheConfig.getLanguageCacheName());
        List<SysLanguage> languages = JSON.parseArray(value.toString(), SysLanguage.class);

        SysLanguage lanEn = languages.stream().
                filter(t -> t.getLanguageName().equals("en-US")).
                collect(Collectors.toList()).get(0);
        SysLanguage lanRu = languages.stream().
                filter(t -> t.getLanguageName().equals("ru-RU")).
                collect(Collectors.toList()).get(0);

        value = this.redisUtils.get(this.systemCacheConfig.getMenuAndLanguageCacheName());
        List<SysMenuLanguage> menuLanguages = JSON.parseArray(value.toString(), SysMenuLanguage.class);

        //region 初始化多语

        List<SysMenuLanguage> enMenu = menuLanguages.stream().
                filter(t -> t.getMenuId().equalsIgnoreCase(root.getId())).
                filter(t -> t.getLanguageId().equalsIgnoreCase(lanEn.getId())).
                collect(Collectors.toList());

        List<SysMenuLanguage> ruMenu = menuLanguages.stream().
                filter(t -> t.getMenuId().equalsIgnoreCase(root.getId())).
                filter(t -> t.getLanguageId().equalsIgnoreCase(lanRu.getId())).
                collect(Collectors.toList());

        if (enMenu.size() > 0) {
            root.setMenuNameEn(enMenu.get(0).getMenuName());
        }

        if (ruMenu.size() > 0) {
            root.setMenuNameRu(ruMenu.get(0).getMenuName());
        }

        //endregion

        //endregion

        List<SysMenuDTO> list = menus.stream().
                filter(t -> !StringUtils.isEmpty(t.getParentId())).
                filter(t -> t.getParentId().equals(root.getId())).
                collect(Collectors.toList());
        if (list.size() > 0) {
            root.setChildren(new ArrayList<>());
            root.getChildren().addAll(list.stream().
                    sorted(Comparator.comparing(SysMenuDTO::getSerialNumber))
                    .collect(Collectors.toList()));
            for (SysMenuDTO item : list) {
                this.initMenuChildren(item, menus);
            }
        }

    }

    //endregion

}
